package 二叉树.二叉树最小深度;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2023/1/30 14:34
 * @description:
 * @version:
 */
public class Solution {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        root.right = new TreeNode(9);
        root.left = new TreeNode(20,new TreeNode(15),new TreeNode(7));
        System.out.println(minDepth(root));
    }


    //利用BFS
    public static int minDepth(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        if (root == null){
            return 0;
        }
        int ans = 0;
        queue.offer(root);
        while (!queue.isEmpty()){
            int size = queue.size();
            while (size > 0){
                TreeNode node = queue.poll();
                if (node.left == null && node.right == null){
                    return ans+1;
                }
                if (node.left != null){
                    queue.offer(node.left);
                }
                if (node.right != null){
                    queue.offer(node.right);
                }
                size--;
            }
            ans++;
        }
        return 0;
    }

    //DFS
    public static int minDepth2(TreeNode root) {
        if (root == null) {
            return 0;
        }

        if (root.left == null && root.right == null) {
            return 1;
        }

        int min_depth = Integer.MAX_VALUE;
        if (root.left != null) {
            min_depth = Math.min(minDepth(root.left), min_depth);
        }
        if (root.right != null) {
            min_depth = Math.min(minDepth(root.right), min_depth);
        }

        return min_depth + 1;
    }
}
